<template>
  <div>
    <template v-for="(item, index) in options" :key="item.value">
      <template v-if="values.includes(item.value)">
        <span
          v-if="
            (item.raw.listClass == 'default' || item.raw.listClass == '') &&
            (item.raw.cssClass == '' || item.raw.cssClass == null)
          "
          :index="index"
          :class="item.raw.cssClass"
          >{{ item.label + ' ' }}</span
        >
        <el-tag
          v-else
          :disable-transitions="true"
          :index="index"
          :type="getTagType(item.raw.listClass)"
          :class="item.raw.cssClass"
        >
          {{ item.label + ' ' }}
        </el-tag>
      </template>
    </template>
    <template v-if="unmatch && showValue">
      {{ formattedUnmatchArray }}
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'

// 定义选项类型
interface DictOption {
  value: string
  label: string
  raw: {
    listClass: string
    cssClass: string | null
  }
}

// 定义Props
interface Props {
  options?: DictOption[]
  value?: number | string | Array<number | string>
  showValue?: boolean
  separator?: string
}

const props = withDefaults(defineProps<Props>(), {
  options: () => [],
  value: undefined,
  showValue: true,
  separator: ',',
})

// 计算values
const values = computed(() => {
  if (props.value === null || typeof props.value === 'undefined' || props.value === '') return []
  return Array.isArray(props.value)
    ? props.value.map((item) => '' + item)
    : String(props.value).split(props.separator)
})

// 计算未匹配项
const unmatchInfo = computed(() => {
  const unmatchArray: string[] = []
  // 没有value不显示
  if (
    props.value === null ||
    typeof props.value === 'undefined' ||
    props.value === '' ||
    !props.options ||
    props.options.length === 0
  )
    return { unmatch: false, unmatchArray }

  // 传入值为数组
  let unmatch = false // 添加一个标志来判断是否有未匹配项
  values.value.forEach((item) => {
    if (!props.options!.some((v) => v.value === item)) {
      unmatchArray.push(item)
      unmatch = true // 如果有未匹配项，将标志设置为true
    }
  })
  return { unmatch, unmatchArray } // 返回标志的值
})

const unmatch = computed(() => unmatchInfo.value.unmatch)
const unmatchArray = computed(() => unmatchInfo.value.unmatchArray)

// 格式化未匹配数组
const formattedUnmatchArray = computed(() => {
  if (unmatchArray.value.length === 0) return ''
  return unmatchArray.value.reduce((pre, cur) => {
    return pre + ' ' + cur
  })
})

// Helper function to get valid tag type
const getTagType = (listClass: string): 'primary' | 'success' | 'warning' | 'danger' | 'info' => {
  const validTypes = ['primary', 'success', 'warning', 'danger', 'info']
  if (validTypes.includes(listClass)) {
    return listClass as 'primary' | 'success' | 'warning' | 'danger' | 'info'
  }
  // For 'default' or any other value, return 'primary' as default type
  return 'primary'
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
